<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { getCorrentProblems, addProblemRecheck } from '@/api/table'
import { ref, unref, reactive, onMounted } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Form, FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import { useValidator } from '@/hooks/web/useValidator'
import { Dialog } from '@/components/Dialog'
import { useForm } from '@/hooks/web/useForm'
import { ElTag } from 'element-plus'
import { searchSchema, rowStyleFC } from './util'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const { t } = useI18n()
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const columns: TableColumn[] = [
  // {
  //   field: 'workTypeName',
  //   label: '作业类型',
  //   sortable: true
  // },
  {
    field: 'problemTypeName',
    label: t('problem.problemType'),
    sortable: true
  },
  {
    field: 'problemContent',
    label: t('problem.problemContent'),
    sortable: true
  },
  {
    field: 'fileName',
    label: t('common.fileName'),
    sortable: true
  },
  {
    field: 'stationName',
    label: '采集站',
    sortable: true
  },
  {
    field: 'depName',
    label: '部门',
    sortable: true
  },

  {
    field: 'userName',
    label: '用户',
    sortable: true
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    sortable: true
  },
  {
    field: 'fileTime',
    label: '拍摄时间',
    sortable: true
  },
  {
    field: 'collectTime',
    label: '采集时间',
    sortable: true
  },
  {
    field: 'checkTime',
    label: '审查时间',
    sortable: true
  },
  {
    field: 'correctContent',
    label: '整改措施',
    sortable: true
  },
  {
    field: 'correctTime',
    label: '整改时间',
    sortable: true
  },
  {
    field: 'recheckContent',
    label: '复检意见'
  },
  {
    field: 'recheckTime',
    label: '复检时间',
    sortable: true
  },
  {
    field: 'recheckUserName',
    label: '审查人',
    sortable: true
  },
  {
    field: 'status',
    label: '状态',
    slots: {
      default: (data: any) => {
        return (
          <>
            {data.row.recheckTime ? (
              <ElTag type={data.row.status === 1 ? 'success' : 'danger'}>
                {data.row.status === 1 ? t('common.agree') : t('common.disagree')}
              </ElTag>
            ) : null}
          </>
        )
      }
    }
  }
  // {
  //   field: 'action',
  //   label: t('userDemo.action'),
  //   slots: {
  //     default: (data: any) => {
  //       return (
  //         <>
  //           <BaseButton type="success" onClick={() => action(data.row)}>
  //             {'下发复检意见'}
  //           </BaseButton>
  //           {/* <BaseButton type="danger" onClick={() => delData(data.row)}>
  //             {t('exampleDemo.del')}
  //           </BaseButton> */}
  //         </>
  //       )
  //     }
  //   }
  // }
]
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')
const action = (row: any) => {
  dialogTitle.value = '下发复检意见'
  currentRow.value = row
  dialogVisible.value = true
}

const delLoading = ref(false)
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getCorrentProblems({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  }
  // fetchDelApi: async () => {
  //   const res = await deleteFiles(unref(ids))
  //   return !!res
  // }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const currentDay = new Date()
function getFormattedDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const fifteenDaysAgo = new Date()
fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 30)
const v = ref([
  getFormattedDate(fifteenDaysAgo) + ' 00:00:00',
  getFormattedDate(currentDay) + ' 23:59:59'
])
const searchParams = ref({ startTime: v.value[0], endTime: v.value[1] })

onMounted(() => {
  setValues({ date: v, depName: userStore.userInfo?.depName })
})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}

const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const saveLoading = ref(false)

const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    saveLoading.value = true
    const formData = await getFormData()
    try {
      formData.guid = currentRow.value?.guid
      let res = await addProblemRecheck(formData).finally(() => {
        saveLoading.value = false
      })
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const formSchema = ref<FormSchema[]>([
  {
    field: 'recheckContent',
    label: '整改意见',
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea'
    }
  }
])

const rules = reactive({
  correctContent: [required()]
})
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="formRegister"
    />

    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :reserveIndex="true"
      :columns="columns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      :showAction="true"
      :rowStyle="rowStyleFC"
    />
    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Form :rules="rules" :schema="formSchema" :isCol="false" @register="formRegister" />
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
